package com.pvdnc.xdynamic.loader.module;

import android.content.Context;
import android.util.Log;

import com.pvdnc.xdynamic.common.ModuleCallResult;
import com.pvdnc.xdynamic.common.ModuleStartArgs;
import com.pvdnc.xdynamic.common.XModule;

import java.util.HashMap;
import java.util.Map;

public class ModuleRecord {
    private static final String TAG=ModuleRecord.class.getSimpleName();

    private final ModuleLoader mLoader;

    private final Class<?> mEntryClass;

    public ModuleRecord(ModuleLoader loader,Class<?> entryClass) {
        mLoader=loader;
        mEntryClass = entryClass;
    }

    public String getModuleName(){
        return mLoader.getModuleName();
    }

    public Context getModuleContext(){
        return mLoader.getModuleContext();
    }

    private final Map<String,XModule> mNamedInstanceMap=new HashMap<>();

    public XModule getOrCreate(String name,boolean alwaysCreate) throws Exception{
        XModule module=null;
        if(!alwaysCreate)
            module= mNamedInstanceMap.get(name);
        if(module!=null)
            return module;
        module= (XModule) mEntryClass.newInstance();
        if(!alwaysCreate)
            mNamedInstanceMap.put(name,module);
        return module;
    }

    public static final String NAME_SINGLETON="singleton";

    public ModuleCallResult callEntry(ModuleStartArgs args) throws Exception {
        Log.d(TAG,"attempt to call entry class:"+mEntryClass
                +" for module:"+mLoader.getModuleName());
        XModule module=null;
        if(args.isSingleton()) {
            module = getOrCreate(NAME_SINGLETON,false);
        }else{
            module=getOrCreate(null,true);
        }
        return module.start(args);
    }

    /**
     * 直接用模块类加载器加载指定类
     * @deprecated 方式不规范，除非特殊情况必要，否则不推荐使用
     */
    public Class<?> loadModuleClass(String className) throws ClassNotFoundException {
        return getModuleContext().getClassLoader().loadClass(className);
    }
}
